package com.luocj.refresh.activity;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.luocj.refresh.R;
import com.luocj.refresh.adapter.ClassicAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;

public class ClassicFreshActivity extends AppCompatActivity {

    private Context mContext;
    private SmartRefreshLayout smartrefreshlayout;
    private RecyclerView recyclerview;
    private ClassicAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classic_fresh);
        mContext = this;
//        initData();
        initView();
    }

    private ArrayList<String> initData() {
        ArrayList<String> mdatas = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            mdatas.add("item :" + i);
        }
        return mdatas;
    }

    private void initView() {
        smartrefreshlayout = findViewById(R.id.smartrefreshlayout);
        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new ClassicAdapter(mContext, null);
        recyclerview.setAdapter(adapter);

        View inflate = LayoutInflater.from(mContext).inflate(R.layout.empty, (ViewGroup) smartrefreshlayout.getParent(), false);
        adapter.setEmptyView(inflate);
        smartrefreshlayout.autoRefresh();


//        设置下拉刷新 上拉加载更多

        smartrefreshlayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refresh(refreshLayout, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                refresh(refreshLayout, true);
            }
        });
    }

    private void refresh(RefreshLayout refreshLayout, final boolean isrefresh) {
        refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isrefresh) {
                    adapter.setNewData(initData());
                    smartrefreshlayout.finishRefresh();
                } else {
                    adapter.addData(initData());
                    smartrefreshlayout.finishLoadMore();
                }
            }
        }, 2000);
    }
}
